package org.martin.snsrs.services;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.martin.snsrs.beans.User;
import org.martin.snsrs.daos.UserDao;
import org.martin.snsrs.utils.MathUtil;
import org.martin.snsrs.utils.SessionUtils;

public class UserServices {
	
	private UserDao userDao;
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public boolean isUserUnique(String username){
		try{
			if(userDao.getUserByUsername(username) == null)
				return true;
			else {
				return false;
			}
		}
		catch(Exception ex){
			
		}
		return false;
	}

	/**
	 * 生成新的SessionID，并存储至数据库中
	 * @param username
	 * @return
	 */
	public String generateSessionKey(String username){
		String key = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy/mm/dd HH:MM:SS");
		key = MathUtil.getMD5(username + format.format(new Date()));
		userDao.saveUserSession(username, key);
		return key;
	}
	
	public Integer getUserBySessionKey(String sessionKey){
		if(SessionUtils.getUserSessionKey() != null)
			return SessionUtils.getUserID();
		else {
			User user = userDao.getUserBySessionKey(sessionKey);
			SessionUtils.setUserID(user.getUserID());
			SessionUtils.setUserSessionKey(sessionKey);
			return user.getUserID();
		}
	}
}
